import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';

///倒计时按钮
class CountDown extends StatefulWidget {
  const CountDown({
    Key? key,
    this.duration = 60,
    this.onTap,
    this.defaultText = '--',
    this.width,
    this.height,
    this.style,
    this.radius,
  }) : super(key: key);

  ///持续时间
  final int duration;

  ///点击事件
  final Future<bool> Function()? onTap;

  ///默认文本
  final String defaultText;

  ///宽
  final double? width;

  ///高
  final double? height;

  ///字体样式
  final TextStyle? style;

  ///圆角
  final double? radius;

  @override
  _CountDownState createState() => _CountDownState();
}

class _CountDownState extends State<CountDown> {
  ///显示的文字
  String? _showText;

  ///持续时间
  int? _duration;

  ///计时器
  Timer? _timer;

  @override
  void setState(Function() fn) {
    if (mounted) {
      super.setState(fn);
    }
  }

  @override
  void initState() {
    super.initState();
    Future<void>.delayed(Duration.zero, () {
      _duration = widget.duration;
      setState(() {});
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  ///开始倒计时
  Future<void> _start() async {
    if (widget.onTap != null) {
      ///是否发送成功
      final bool _success = await widget.onTap!();

      if (_success) {
        _duration = _duration! - 1;

        _showText = '${_duration.toString().padLeft(2, '0')}s';

        setState(() {});

        _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
          _duration = _duration! - 1;

          _showText = '${_duration.toString().padLeft(2, '0')}s';

          if (_duration == 0) {
            _timer?.cancel();

            _timer = null;

            _showText = null;

            _duration = widget.duration;
          }

          setState(() {});
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppBtn.noPadding(
      width: widget.width ?? 90,
      height: widget.height ?? 40,
      alignment: Alignment.center,
      text: _showText ?? '获取验证码',
      textStyle: TextStyle(
        color: theme(context).withOpacity(
          _duration == widget.duration && widget.onTap != null ? 1 : 0.7,
        ),
      ),
      onTap: _duration == widget.duration && widget.onTap != null ? () async => await _start() : null,
      disabledColor: Colors.transparent,
      color: Colors.transparent,
    );
  }
}
